from odoo import api, models, fields
from odoo.exceptions import  ValidationError


class SbPackingDelivery(models.Model):
    _inherit = 'sb.packing.delivery'

    def pack_done(self):
        """增加发货锁定校验
        厂编锁定、销售单锁定、datecode锁定
        """
        for rec in self.pick_lists:
            sale_order_id = rec.shipping_instructions_line_id.sale_order_id
            # 锁销售订单
            if sale_order_id.s_disable_delivery:
                lock_id = sale_order_id.s_erp_lock_id
                if lock_id:
                    raise ValidationError('销售单【{}】已锁定无法发货\n锁定人: {}\n锁定时间:{}\n锁定原因:{}'.format(sale_order_id.name, lock_id.create_uid.name, lock_id.create_date, lock_id.note))
                else:
                    raise ValidationError('销售单【{}】已锁定无法发货'.format(sale_order_id.name))

            # 锁定产品校验
            if sale_order_id.product_id.s_disable_delivery:

                lock_id = sale_order_id.product_id.s_erp_lock_id
                if lock_id:
                    raise ValidationError(
                        '产品【{}】已锁定无法发货\n锁定人: {}\n锁定时间:{}\n锁定原因:{}'.format(sale_order_id.product_id.name,
                                                                                                lock_id.create_uid.name,
                                                                                                lock_id.create_date,
                                                                                                lock_id.note))
                else:
                    raise ValidationError('产品【{}】已锁定无法发货'.format(sale_order_id.product_id.name))

            # 锁定周期码
            datecode_ids = self.env['s.datecode.cache'].sudo().search([('s_disable_delivery', '=', True)])
            datecode_pack = set(rec.datecode_line_ids.mapped('datecode'))
            datecode_maps = set(datecode_ids.mapped('name'))
            # 求同
            lock_datecode = datecode_pack.intersection(datecode_maps)
            if lock_datecode:
                for d in datecode_ids:
                    if d.name in lock_datecode:
                        lock_id = d.s_erp_lock_id
                        raise ValidationError("DateCode: {}已锁定，不允许发货!\n锁定人:{}\n锁定时间:{}\n锁定原因:{}".format(d.name, lock_id.create_uid.name, lock_id.create_date, lock_id.note))
        return super().pack_done()